<template>
  <div class="sidebar-favorites" v-if="isSidebarVisible">
    <div class="sidebar-header">
      <h3>我的收藏夹</h3>
      <button class="close-btn" @click="toggleSidebar">&times;</button>
    </div>
    <div class="sidebar-content">
      <div v-if="favorites.length === 0" class="empty-favorites">
        <p v-if="!isLoggedIn">请先登录查看收藏夹</p>
        <p v-else-if="loadError">加载收藏夹失败：{{ errorMessage }}</p>
        <p v-else>暂无收藏商品</p>
      </div>
      <div v-else class="favorites-list">
        <div 
          v-for="item in favorites" 
          :key="item.id" 
          class="favorite-item"
          @click="viewProduct(item.productId)"
        >
          <img :src="getProductImage(item.productImage)" :alt="item.productName" class="favorite-image" />
          <div class="favorite-info">
            <p class="favorite-name">{{ item.productName }}</p>
          </div>
          <button class="remove-btn" @click.stop="removeFavorite(item.productId)">&times;</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getFavorites, getFavoriteItems, removeFavorite, createFavorite } from '@/api/favoriteApi'

export default {
  name: 'SidebarFavorites',
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isSidebarVisible: true,
      favorites: [],
      defaultCollectId: '',
      loadError: false,
      errorMessage: ''
    }
  },
  watch: {
    // 监听用户登录状态变化
    isLoggedIn: {
      handler(newVal) {
        if (newVal) {
          this.loadFavorites()
        } else {
          this.favorites = []
        }
      },
      immediate: true
    },
    // 监听用户ID变化
    userId: {
      handler(newVal) {
        if (newVal) {
          this.loadFavorites()
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 页面加载时获取收藏夹数据
    if (this.isLoggedIn && this.userId) {
      this.loadFavorites()
    }
  },
  methods: {
    toggleSidebar() {
      this.isSidebarVisible = !this.isSidebarVisible
    },
    async loadFavorites() {
      try {
        // 重置错误状态
        this.loadError = false
        this.errorMessage = ''
        
        // 获取用户的收藏夹数据
        if (this.userId) {
          let response;
          try {
            response = await getFavorites(this.userId)
          } catch (error) {
            // 如果获取收藏夹失败，可能是因为没有创建默认收藏夹
            if (error.message && error.message.includes('获取收藏夹失败')) {
              // 创建默认收藏夹
              await createFavorite(this.userId, '默认收藏夹')
              // 再次尝试获取收藏夹
              response = await getFavorites(this.userId)
            } else {
              throw error
            }
          }
          
          // 查找默认收藏夹
          const collects = Array.isArray(response) ? response : response.data || []
          const defaultCollect = collects.find(collect => collect.name === '默认收藏夹')
          if (defaultCollect) {
            this.defaultCollectId = defaultCollect.id
          } else if (collects.length > 0) {
            // 如果没有默认收藏夹，使用第一个收藏夹
            this.defaultCollectId = collects[0].id
          } else {
            // 如果没有任何收藏夹，创建默认收藏夹
            const createResponse = await createFavorite(this.userId, '默认收藏夹')
            if (createResponse === 'success') {
              // 再次获取收藏夹
              const newResponse = await getFavorites(this.userId)
              const newCollects = Array.isArray(newResponse) ? newResponse : newResponse.data || []
              const newDefaultCollect = newCollects.find(collect => collect.name === '默认收藏夹')
              if (newDefaultCollect) {
                this.defaultCollectId = newDefaultCollect.id
              }
            }
          }
          
          // 获取默认收藏夹中的商品
          if (this.defaultCollectId) {
            const itemsResponse = await getFavoriteItems(this.userId, this.defaultCollectId)
            this.favorites = Array.isArray(itemsResponse) ? itemsResponse : itemsResponse.data || []
          }
        }
      } catch (error) {
        console.error('加载收藏夹数据失败:', error)
        this.loadError = true
        this.errorMessage = error.message || '未知错误'
      }
    },
    viewProduct(productId) {
      this.$router.push({ name: 'ProductDetail', params: { id: productId } })
    },
    async removeFavorite(productId) {
      try {
        if (this.userId && productId && this.defaultCollectId) {
          await removeFavorite(this.userId, productId, this.defaultCollectId)
          // 从本地列表中移除
          this.favorites = this.favorites.filter(item => item.productId !== productId)
          this.$message.success('已从收藏夹移除')
          // 通知父组件更新
          this.$emit('favorite-updated')
        }
      } catch (error) {
        console.error('移除收藏失败:', error)
        this.$message.error('移除收藏失败')
      }
    },
    
    // 获取商品图片
    getProductImage(fileName) {
      // 确保 fileName 存在且不为空
      if (!fileName) {
        try {
          return require('@/assets/images/default_product.jpg');
        } catch (error) {
          console.error('默认图片加载失败:', error);
          return ''; // 返回空字符串作为最后的备选方案
        }
      }
      
      try {
        // 先尝试从 assets/files 目录加载
        const imageModule = require(`@/assets/files/${fileName}`);
        return imageModule;
      } catch (error) {
        // 如果图片不存在，尝试从 public/images 目录加载
        try {
          const imageModule = require(`@/assets/images/${fileName}`);
          return imageModule;
        } catch (secondError) {
          // 如果都不存在，返回默认图片
          console.warn(`商品图片加载失败: ${fileName}`, error);
          try {
            return require('@/assets/images/default_product.jpg');
          } catch (defaultError) {
            console.error('默认图片加载失败:', defaultError);
            return ''; // 返回空字符串作为最后的备选方案
          }
        }
      }
    },
    
  }
}
</script>

<style scoped>
.sidebar-favorites {
  width: 250px;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.sidebar-content {
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.empty-favorites {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.favorite-item {
  display: flex;
  gap: 10px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.favorite-item:hover {
  border-color: #ff6700;
  box-shadow: 0 0 5px rgba(255, 103, 0, 0.2);
}

.favorite-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 3px;
}

.favorite-info {
  flex: 1;
}

.favorite-name {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.favorite-price {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  color: #ff6700;
}

.remove-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-btn:hover {
  background: #ff6700;
}
</style>